import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { FormattedMessage, history } from 'umi';
import { Button, Modal, Drawer, message, Typography, Space, Tag, Tooltip, Badge } from 'antd';
import ProDescriptions from '@ant-design/pro-descriptions';
import { queryOrderListSys } from '@/services/ant-design-pro/apis';
const { Text, Link } = Typography;
const Role = (props) => {
  const actionRef = useRef();
  const [selectRows, setSelectRows] = useState([]);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormVals, setStepFormVals] = useState({});
  const [row, setRow] = useState();
  const [stepVals, setStepVals] = useState({});
  const [authModalVisible, handleAuthModalVisible] = useState(false);
  const [authSelectRows, setAuthSelectRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [stepAuths, setStepAuths] = useState([]);
  const [updateOrder, setUpdateOrder] = useState(false);
  const [refundTypeList, setRefundTypeList] = useState([]);
  const [refundModalVisible, handleRefundModalVisible] = useState(false);

  function download() {
    const aLink = document.createElement('a');
    document.body.appendChild(aLink);
    aLink.style.display = 'none';
    aLink.href = '/api/Export';
    aLink.click();
    document.body.removeChild(aLink);
  }

  function formatDate() {
    var date = new Date();
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return YY + MM + DD + ' ' + hh + mm + ss;
  }

  const handleExport = async (form) => {
    const value = await form.validateFields();
    if (value?.dateTimeRange != null) {
      value.dateTimeRange = [
        value.dateTimeRange[0].format('YYYY-MM-DD'),
        value.dateTimeRange[1].format('YYYY-MM-DD'),
      ];
    }
    const hide = message.loading('正在导出', 600000);
    try {
      await AgentOrderExport({ ...value }).then((res) => {
        let url = URL.createObjectURL(new Blob([res]));
        let filename = formatDate() + '.xlsx';
        let a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        URL.revokeObjectURL(url);
      });
      hide();
      message.success('导出成功');
      actionRef.current.reload();
    } catch (error) {
      hide();
      console.log(error);
      message.error('导出失败');
    }
  };

  const OrderInfo = (entity) => {
    var status = <Badge status="error" text="未知"></Badge>;
    if (entity?.orderStatus == 'SUCCESS') {
      status = <Badge status="success" text="充值成功"></Badge>;
    } else if (entity?.orderStatus == 'FAILED') {
      status = <Badge status="default" text="充值失败"></Badge>;
    } else if (entity?.orderStatus == 'IN_PROCESS') {
      status = <Badge status="processing" text="充值中"></Badge>;
    } else if (entity?.orderStatus == 'ERROR') {
      status = <Badge status="processing" text="支付成功，同步异常"></Badge>;
    } else if (entity?.orderStatus == 'WAIT_FOR') {
      status = <Badge status="processing" text="同步成功，待回调"></Badge>;
    } else if (entity?.orderStatus == 'TIMEOUT') {
      status = <Badge status="processing" text="超时未支付"></Badge>;
    } else if (entity?.orderStatus == 'NON_PAYMENT') {
      status = <Badge status="error" text="未支付"></Badge>;
    }

    return (
      <Space direction="vertical" key={entity?.orderNo}>
        <Text>{entity?.orderNo}</Text>
        <Text>订单状态: {status}</Text>
        <Text type="success">目标账号:{entity?.account}</Text>
      </Space>
    );
  };

  const TypeInfo = (entity) => {
    if (entity?.productType == 'Direct') {
      return <Tag color="red">直充</Tag>;
    }
    if (entity?.productType == 'Card' || entity?.productType == 'Direct') {
      return (
        <Tag
          color="cyan"
          onClick={() => {
            setStepFormVals(entity);
            handleUpdateModalVisible(true);
          }}
        >
          卡密
        </Tag>
      );
    }
  };

  const columns = [
    {
      title: '用户信息',
      dataIndex: 'userInfo',
      hideInForm: true,
      search: false,
      hideInSearch: true,
      render: (demo, entity) => [
        <Space direction="vertical" key={entity.id}>
          <Text>{entity.name}</Text>
          <Text>{entity.phone}</Text>
          <Text>{entity.gmtCreate}</Text>
        </Space>,
      ],
    },
    {
      title: '订单消息',
      dataIndex: 'agentOrderCode',
      hideInSearch: true,
      render: (demo, entity) => [OrderInfo(entity)],
    },
    {
      title: '产品信息',
      dataIndex: 'productId',
      hideInSearch: true,
      render: (demo, entity) => [
        <Space direction="vertical" key={entity.id}>
          <Text>{TypeInfo(entity)}</Text>
          <Text>{entity.productName}</Text>
          <Text type="success">
            数量:{entity.num} x 单价:{entity.productPrice}
          </Text>
          <Text type="success">金额:{entity.totalPrice}</Text>
        </Space>,
      ],
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      hideInTable: true,
    },
    {
      title: '充值号码',
      dataIndex: 'account',
      hideInTable: true,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      hideInTable: true,
    },
    {
      title: '用户账号',
      dataIndex: 'phone',
      hideInTable: true,
    },
    {
      title: '时间',
      dataIndex: 'dateTimeRange',
      hideInTable: true,
      valueType: 'dateRange',
    },
    {
      title: '订单状态',
      dataIndex: 'OrderStatus',
      hideInTable: true,
      valueEnum: () => {
        return {
          SUCCESS: {
            text: '充值成功',
          },
          IN_PROCESS: {
            text: '订单同步中',
          },
          ERROR: {
            text: '订单同步异常',
          },
          FAILED: {
            text: '充值失败',
          },
          WAIT_FOR: {
            text: '等待状态更新',
          },
          NON_PAYMENT: {
            text: '待支付',
          },
          TIMEOUT: {
            text: '超时未支付',
          },
        };
      },
      formItemProps: {
        initialValue: undefined,
      },
    },
    {
      title: '用户备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '订单提示',
      dataIndex: 'errorMsg',
      hideInSearch: true,
    },
    ,
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Link
          key="info"
          onClick={() => {
            // history.push({
            //     pathname:'/order/agentOderInfo',
            //     query:{
            //         orderId:record.id
            //     }
            // });
            window.open('/#/order/orderInfo?orderId=' + record.id);
          }}
        >
          详情
        </Link>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        headerTitle="业务订单列表"
        actionRef={actionRef}
        // toolBarRender={(searchConfig) => [
        //     <Button type="primary" >导出</Button>
        // ]}
        request={queryOrderListSys}
        rowKey="id"
        rowSelection={{
          onChange(_, selectRows) {
            setSelectRows(selectRows);
          },
        }}
        search={{
          optionRender: ({ searchText, resetText }, { form }, dom) => [
            <Button
              key="searchText"
              type="primary"
              onClick={() => {
                form?.submit();
              }}
            >
              {searchText}
            </Button>,
            <Button
              key="resetText"
              onClick={() => {
                form?.resetFields();
              }}
            >
              {resetText}
            </Button>,
            <Button
              type="primary"
              key="export"
              onClick={() => {
                handleExport(form);
              }}
            >
              导出订单
            </Button>,
          ],
        }}
      ></ProTable>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions
            column={2}
            title={row.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row.name,
            }}
            columns={columns}
          ></ProDescriptions>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default Role;
